package service

import (
	"fmt"
	"hanyun-admin/src/entity"
	"log"
)

//根据用户id查询当前的岗位数据
func SelectPostsByUserId(userId int64) entity.Post {
	var post entity.Post
	_, err := DbEngine.Table("sys_post").Alias("p").
		Join("LEFT", []string{"sys_user_post", "up"}, "up.post_id=p.post_id").
		Join("LEFT", []string{"sys_user", "u"}, "u.user_id=up.user_id").
		Where("u.user_id = ?", userId).Get(&post)
	if err != nil {
		fmt.Println("select post by userId error", err)
	}
	return post
}

//查询数据列表
func SelectPostList(post entity.Post) []entity.Post {
	postList := make([]entity.Post, 0)
	sql := DbEngine.Select("*")
	if post.PostCode != "" {
		//这是模糊查询的写法
		sql.Where("post_code like ?", "%"+post.PostCode+"%")
	}
	if post.PostName != "" {
		sql.Where("post_name like ?", "%"+post.PostName+"%")
	}
	if post.Status != "" {
		sql.Where("status = ?", post.Status)
	}
	err := sql.Limit(post.PageSize, (post.PageNum-1)*post.PageSize).Find(&postList)
	if err != nil {
		fmt.Println("select post list error ", err)
	}
	return postList
}

//根据条件查询总条数
func SelectPostListCount(post entity.Post) int {
	sql := DbEngine.Select("count(0)")
	if post.PostCode != "" {
		//这是模糊查询的写法
		sql.Where("post_code like ?", "%"+post.PostCode+"%")
	}
	if post.PostName != "" {
		sql.Where("post_name like ?", "%"+post.PostName+"%")
	}
	if post.Status != "" {
		sql.Where("status = ?", post.Status)
	}
	count, err := sql.Count(entity.Post{})
	if err != nil {
		fmt.Println("select post list count error", err)
		return 0
	}
	fmt.Println(count)
	return int(count)
}

//根据id查询数据详情
func SelectPostInfoByPostId(postId int64) entity.Post {
	var post entity.Post
	_, err := DbEngine.Id(postId).Get(&post)
	if err != nil {
		fmt.Println("select post by postId error", err)
	}
	return post
}

//添加数据
func InsertSysPost(post entity.Post) error {
	_, err := DbEngine.Insert(post)
	return err
}

//更新数据
func UpdateSysPostData(post entity.Post) error {
	_, err := DbEngine.Id(post.PostId).Update(post)
	return err
}

//删除
func DeleteSysPostByPostId(postId int64) error {
	//需要一个空的结构体 xorm需要进行映射
	post := new(entity.Post)
	_, err := DbEngine.Id(postId).Delete(post)
	return err
}

//获取全部岗位信息
func SelectPostAll() []entity.Post {
	post := make([]entity.Post, 0)
	err := DbEngine.Find(&post)
	if err != nil {
		log.Println("select post all by error ", err)
	}
	return post
}

func SelectPostListByUserId(userId int64) []int64 {
	post := make([]entity.Post, 0)
	err := DbEngine.Alias("p").Join("LEFT", []string{"sys_user_post", "up"}, "up.post_id=p.post_id").
		Join("LEFT", []string{"sys_user", "u"}, "u.user_id = up.user_id").Where("u.user_id = ?", userId).Find(&post)
	if err != nil {
		log.Println("select post by userId error ", err)
	}
	postIdList := make([]int64, 0)
	for _, v := range post {
		postIdList = append(postIdList, v.PostId)
	}
	return postIdList
}
